package com.yqg.demo.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.concurrent.CopyOnWriteArraySet;

@Component
@ServerEndpoint("/websocket/getdata")
@Slf4j
public class WebSocketServer {
    private static volatile String remessage;


    // 要注入的组件
    private static String nwIpAddress;

    @Autowired
    public void setSendConfig(Ipconig ipconig){
        WebSocketServer.nwIpAddress = ipconig.getNwIpAddress();
    }


    private static CopyOnWriteArraySet<WebSocketServer> webSockets = new CopyOnWriteArraySet<>();

    private Session session = null;

    @OnOpen
    public void onOpen(Session session) throws IOException {
        log.info("connected，nwIpAddress!" +nwIpAddress);
        this.session = session;
        webSockets.add(this);
    }

    @OnClose
    public void onClose() throws IOException {
        log.info("disconnected!");
        this.session.close();
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("receive message!");
        sendDatatonw(message);
    }

    public void sendMessage(String message) {
// synchronized (this.session) {
//            try {
//                this.session.getBasicRemote().sendText(message);
//            } catch (IOException e) {
//                log.error(e.getMessage());
//            }
        for (WebSocketServer webSocket : webSockets) {
            try {
                if (webSocket.session.isOpen()) {
                    webSocket.session.getAsyncRemote().sendText(message);
                }
            } catch (Exception e) {
                e.printStackTrace();
                log.error("全部人员发送消息失败：", e.getMessage());
            }
        }

    }

    //@PostConstruct
    public void init() {
        //接受内网数据
        Thread thread = new Thread() {
            //重写方法
            @Override
            public void run() {
                DatagramSocket socket = null;
                try {
                    socket = new DatagramSocket(56781);
                } catch (SocketException e) {
                    e.printStackTrace();
                }
                while (true) {
                    try {
                        //开放端口接收消息
                        //准备接收
                        byte[] data = new byte[1024];
                        DatagramPacket packet = new DatagramPacket(data, 0, data.length);
                        socket.receive(packet);    //接收数据包
                        //过滤byte数组中的空白位置
                        int k = 0;
                        for (byte dataum : data) {
                            if (dataum != (byte) 0) {
                                k++;
                            }
                        }
                        //断开连接
                        byte[] datas = packet.getData();
                        String receivedata = new String(datas, 0, k);
                        synchronized (WebSocketServer.class) {
                            remessage = receivedata;
                        }
                    /*    log.info(new Date() + ",获取到药品出售的用户信息:" + remessage);
                        String encoding = getEncoding(remessage);
                         log.info("当前编码形式encoding，"+ encoding);*/

                        byte[] cloneBytes = datas.clone();
                        String xmlMessage = null;
                        xmlMessage = new String(cloneBytes, StandardCharsets.UTF_8).trim();
                        log.info("接受数据编码转化，"+ xmlMessage);
                        sendMessage(xmlMessage);
                        if (receivedata.equals("bye")) {
                            break;    //监测到结束指令
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                socket.close();
            }
        };
        thread.start();
    }

    /**
     * 发送数据到内网唤起医保设备
     */
    private void sendDatatonw(String message) {
        DatagramSocket socket = null;
        try {
            socket = new DatagramSocket();    //建立套接字   124.167.249.190
            byte[] datas = message.getBytes(StandardCharsets.UTF_8);
            DatagramPacket packet = new DatagramPacket(datas, 0, datas.length, new InetSocketAddress(nwIpAddress, 8765));
            socket.send(packet);    //发送数据包
            log.info(nwIpAddress + "," + new Date() + "发送消息：" + message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
